package com.aaa.mrcai.service.impl;


import com.aaa.mrcai.mapper.GoodsGradeMapper;
import com.aaa.mrcai.pojo.entity.GoodsGrade;
import com.aaa.mrcai.pojo.vo.GoodsGradeVo;
import com.aaa.mrcai.query.GoodsGradeQuery;
import com.aaa.mrcai.result.AjaxResult;
import com.aaa.mrcai.service.GoodsGradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Demo class
 *
 * @Author: Wang
 * @Date: Created in 0:07 2021/12/7
 */
@Service
public class GoodsGradeServiceImpl implements GoodsGradeService {
    @Autowired
    private GoodsGradeMapper goodsGradeMapper;

    @Autowired
    private HttpSession session;


    @Override
    public AjaxResult list(GoodsGradeQuery query) {
        List<GoodsGrade> goodsGrade= goodsGradeMapper.queryGoodsGrade(query);
        Long totalCount = goodsGradeMapper.queryGoodsGradeTotalCount(query);

        Map<Object, Object> map = new HashMap<>();
        map.put("currentPageData",goodsGrade);
        map.put("currentDataTotal", totalCount);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult addGoodsGrade(GoodsGradeVo goodsGradeVo) {
        long count = goodsGradeMapper.isGoodsGradeExists(goodsGradeVo.getGtype());
        if (count > 0) {
            return AjaxResult.defeated("对不起，商品等级已存在");
        }
        int i = goodsGradeMapper.addGoodsGrade(goodsGradeVo);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.defeated();
    }

    @Override
    public AjaxResult getGoodsGrade(int id) {
        GoodsGradeVo r = goodsGradeMapper.getGoodsGrade(id);
        session.setAttribute("currentUpdateGoodsGrade",r);
        return AjaxResult.success(r);
    }

    @Override
    public AjaxResult updateGoodsGrade(GoodsGradeVo goodsGradeVo) {
        GoodsGradeVo currentUpdateGoodsGrade = (GoodsGradeVo) session.getAttribute("currentUpdateGoodsGrade");

        if (!goodsGradeVo.getId().equals(currentUpdateGoodsGrade.getId())){
            return AjaxResult.defeated("不可以乱改哦");

        }
        long count = goodsGradeMapper.isUpdateGoodsGradeExists(goodsGradeVo);

        if (count > 0) {
            return AjaxResult.defeated("已存在该商品等级");
        }

        int i = goodsGradeMapper.updateGoodsGrade(goodsGradeVo);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.defeated();
    }

    @Override
    public AjaxResult deleteGoodsGrade(int id) {
        int  r = goodsGradeMapper.deleteGoodsGrade(id);
        session.setAttribute("currentUpdateGoodsGrade",r);
        return AjaxResult.success(r);
    }
}
